package org.rcy.ruicingmarket.login;

import org.apache.commons.lang3.StringUtils;
import org.rcy.framework.cache.redis.CommonCache;
import org.rcy.ruicingmarket.common.base.ServiceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/10 16:21
 */

@Service
public class CaptchaService {

	@Autowired
	private CommonCache commonCache;

	public String getSID(String sid){
		String cacheData = null;
		String cacheKey;
		if(StringUtils.isNotBlank(sid)) {
			cacheData = (String)commonCache.getData(ServiceType.OSSSERVICE,sid);
		}
		if(StringUtils.isBlank(cacheData)) {
			cacheKey = UUID.randomUUID().toString();
			commonCache.cache(ServiceType.OSSSERVICE,cacheKey,"1",5*60);
		}else {
			cacheKey = sid;
		}
		return cacheKey;
	}

	public void cacheCode(String sid,String code){
		commonCache.cache(ServiceType.OSSSERVICE,sid,code,5*60);
	}

	public boolean verifyCode(String sid,String code){
		String origincode = (String)commonCache.getData(ServiceType.OSSSERVICE,sid);
		if(StringUtils.isBlank(origincode)) {
			return false;
		}
		 return toLowerCase(origincode).equals(toLowerCase(code));
	}

	public void removeCacheCode(String sid){
		commonCache.remove(ServiceType.OSSSERVICE,sid);
	}

	private String toLowerCase(String str){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			if(str.charAt(i) >='A' && str.charAt(i) <= 'Z') {
				sb.append((char)(str.charAt(i)+32));
				continue;
			}
			sb.append(str.charAt(i));
		}
		return sb.toString();
	}
}
